package com.hhit.collaborative_learning.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadFileServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String realDataName=request.getParameter("realDataName");
		String storeDataName=request.getParameter("storeDataName");
		File dfile = new File(getServletContext().getRealPath("/uploadFile"),storeDataName);
		FileInputStream in = new FileInputStream(dfile);  
		//获取文件名字，并对其进行编码，如果不这样会出现中文乱码。至少用这种方式我暂时还没有出现过乱码  
		realDataName = new String(realDataName.getBytes(),"iso8859-1");  
		//通过response对象获得输出流  
		OutputStream out = response.getOutputStream();  
		//  
		response.setContentType("Application/Octet-stream;charset=utf-8");  
		// 下载文件的名字通过这里设置  
		response.addHeader("Content-Disposition", "attachment; filename="+realDataName);  
		   // 下面两句代码功能应该是一样的，都写上去会有异常，说重复设置响应头。  
		// 但是只写第二句的时候用迅雷无法下载。而只写第一句文件可以下载，麻烦知道的朋友可以告诉我一下  
		response.setContentLength((int) dfile.length());  
		        //response.addHeader("Content-Length::", dfile.length() + "");  
		// 下面是一个普通的流的复制 。。。忽略  
		byte[] bs =new byte[1024];  
		int len = 0;  
		while((len =in.read(bs))!=-1){  
		    out.write(bs);  
		}  
		// 最后是流的关闭。  
		out.close();  
		in.close(); 
	}

}
